package io.github.annyylxyms.gyncache.core;

import io.github.annyylxyms.gyncache.command.*;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * register commands here
 * @author Anny
 * @date 2025/1/3 17:25
 */
public class Commands {
    //HashMap会导致输出命令的顺序乱了，用LinkedHashMap即可按顺序输出
    //private static Map<String, Command> All = new HashMap<>();
    private static Map<String, Command> All = new LinkedHashMap<>();

    //代码作用：加载的时候执行静态块的时候执行initCommands，并注册命令
    static {
        initCommands();
    }

    private static void initCommands() {
        // 也可以通过spring bean @Autuwire注解自动注册, 但是需要手动注册,并且如果想要控制输出comman的顺序，需要通过给类加@Order注解控制顺序，老师想避免用Order散开去写， 所以没有通过spring bean的注入方式去注册bean，而是在这里集中写，通过LinkedHashMap控制COMMAND命令输出显示的顺序。
        // common command
        register(new PingCommand());
        register(new InfoCommand());
        register(new CommandCommand());

        // string
        register(new SetCommand());
        register(new GetCommand());
        register(new StrlenCommand());
        register(new DelCommand());
        register(new ExistsCommand());
        register(new IncrCommand());
        register(new DecrCommand());
        register(new MsetCommand());
        register(new MgetCommand());

        // list
        register(new LpushCommand());//从头
        register(new LpopCommand());
        register(new RpushCommand());//从尾
        register(new RpopCommand());
        register(new LindexCommand());
        register(new LrangeCommand());
        register(new LlenCommand());

        //set
        register(new SaddCommand());
        register(new SmembersCommand());
        register(new ScardCommand());
        register(new SremCommand());
        register(new SpopCommand());
        register(new SismemberCommand());

        //hash
        register(new HsetCommand());
        register(new HgetCommand());
        register(new HdelCommand());
        register(new HlenCommand());
        register(new HgetallCommand());
        register(new HmgetCommand());
        register(new HexistsCommand());

        //zset
        register(new ZaddCommand());
        register(new ZcardCommand());
        register(new ZcountCommand());
        register(new ZrankCommand());
        register(new ZremCommand());
        register(new ZscoreCommand());



    }

    /**
     * 注册命令
     * @param command
     */
    public static void register(Command command) {
        All.put(command.name(), command);
    }

    public static Command get(String name) {
        return All.get(name);
    }

    /**
     * 拿到所有key转为数组
     * @return
     */
    public static String[] getCommandNames() {
        return All.keySet().toArray(new String[0]);
    }
}
